package com.xy.usermanagement.readermanagement.controller;

import com.xy.model.Readers;
import com.xy.model.PageList;
import com.xy.model.RestfulResult;
import com.xy.usermanagement.readermanagement.service.IReaderManagementService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping(value = "/readermanagement")
public class ReaderManagementController {
		@Autowired
		private IReaderManagementService readerManagementService;

		@GetMapping(value = "/")
		public RestfulResult list(Integer pageNum, Integer pageSize){
				PageList<Readers> list = readerManagementService.queryForPage(pageNum, pageSize);
				return RestfulResult.success(list);
		}
		@GetMapping(value = "/{name}")
		public RestfulResult getOne(@PathVariable String name) {
				if (name==null||name.equals("")){
						return RestfulResult.failed("400","查询的作者名不能为空");
				}
				Readers readers=null;
				try {
						readers = readerManagementService.getById(name);
				}catch (Exception e){
						return RestfulResult.failed("500","服务正忙，请稍后再试！");
				}
				return RestfulResult.success(readers);
		}

		@PostMapping(value = "/")
		public RestfulResult add(@ModelAttribute Readers readers){
				Readers auth = null;
				Integer i = null;
				log.info("ReadersManagementController add=>"+readers);
				try{
						if (readers==null||readers.getNickName().equals("")){
								return RestfulResult.failed("500","添加失败，请检查插入参数!");
						}
						auth = readerManagementService.getById(readers.getNickName());
						log.info("ReadersManagementController add auth=>"+auth);
						if (auth!=null){
								return RestfulResult.failed("500","添加失败，作者以存在");
						}
						i =readerManagementService.add(readers);
				}catch (Exception e){
						log.error("错误消息：{}", e.getMessage(), e);
						return RestfulResult.failed("500","添加失败，作者以存在");
				}

				return RestfulResult.success(i);
		}

		@PutMapping(value = "/{name}", produces = "application/json;charset=UTF-8")
		@Transactional
		public RestfulResult update(@PathVariable String name,@RequestBody Readers readers){
				log.info("ReadersManagementController update Readers=>"+readers);
				try {
						if(name.equals("")){
								return RestfulResult.failed("500","修改的作者名不能为空！");
						}else if(readerManagementService.getById(name)==null){
								return RestfulResult.failed("500","更新的作者不存在，请输入正确的作者名！");
						}
						readers.setNickName(name);
						readerManagementService.update(readers);
				}catch (Exception e){
						log.error("错误消息：{}", e.getMessage(), e);
						return RestfulResult.failed("500","修改失败");
				}
				return RestfulResult.success();
		}

		@DeleteMapping(value = "/{name}")
		public RestfulResult delete(@PathVariable String name){
				log.info("ReadersManagementController delete names=>"+name);
				return RestfulResult.success();
		}
}
